//
//  Status.swift
//  CXCWeibo
//
//  Created by cxc on 15/7/1.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit
import SDWebImage

 /// 访问微博首页 URL
private let WB_Home_Timeline_URL = "2/statuses/home_timeline.json"

class Status: NSObject {
    // MARK: - 模型属性
    var created_at: String?
    // 微博id
    var id: Int = 0
    var text: String?
    var source: String?
    // 配图数组
    var pic_urls:[[String:String]]?{
        didSet{
            imageURLs = [NSURL]()
            largeImageURLs = [NSURL]()
            for dict in pic_urls!{
                var urlString = dict["thumbnail_pic"]!
                
                imageURLs?.append(NSURL(string: urlString)!)
                
                urlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                largeImageURLs?.append(NSURL(string: urlString)!)
            }
        }
    }
    var imageURLs:[NSURL]?
    var user: User?
    var retweeted_status:Status?
    //大图地址
    var picURLs: [NSURL]? {
        return retweeted_status != nil ? retweeted_status?.imageURLs : imageURLs
    }
    private var largeImageURLs:[NSURL]?
    var largePicURLs:[NSURL]?{
        return retweeted_status != nil ?retweeted_status?.largeImageURLs :largeImageURLs
    }
    
    /**
    *  类属性数组
    */
    static let properties = ["created_at","id","text","source","pic_urls","user","retweeted_status"]
    /**
    *  字典转模型
    */
    init(dict:[String:AnyObject]){
        super.init()
        for key in Status.properties{
            if dict[key] == nil || key == "user" || key == "retweeted_status" {
                continue
            }
            setValue(dict[key], forKey: key)
        }
        if let userDict = dict["user"] as? [String:AnyObject]{
            user = User(dict: userDict)
        }
        
        if let retweetedDict = dict["retweeted_status"] as? [String:AnyObject] {
            retweeted_status = Status(dict:retweetedDict)
        }
    }
    override var description: String {
        let dict = dictionaryWithValuesForKeys(Status.properties)
        
        return "\(dict)"
    }
    /**
    *  加载数据
    */
    class func loadStatus(since_id:Int, max_id:Int, finished:(statuses:[Status]?,error:NSError?) ->()){
        assert(sharedUserAccount != nil, "必须登陆之后才能访问")
        
        var params = ["access_token":sharedUserAccount!.access_token];
        if since_id > 0{
            params["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            params["since_id"] = "0"
            params["max_id"] = "\(max_id - 1)"
        }
        //网路请求数据
        NetworkTools.sharedNetworkTools().GET(WB_Home_Timeline_URL, parameters: params, success: { (_, JSON) -> Void in
            if let array = JSON["statuses"] as? [[String:AnyObject]]{
                let list = statuses(array)
                
                //异步缓存微博数组中的所有图像
                cacheWebImages(list,finished:finished)
                
                return
            }
            finished(statuses: nil, error: nil)
            }) { (_, error) -> Void in
                print(error)
                finished(statuses: nil, error: error)
        }
    }
    /// 利用调度组缓存所有图像
    private class func cacheWebImages(list:[Status],finished:(statuses:[Status]?,error:NSError?) ->()){
        let group = dispatch_group_create()
        
        for s in list{
            if s.imageURLs == nil || s.imageURLs!.isEmpty{
                continue
            }
            for url in s.imageURLs!{
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                    dispatch_group_leave(group)
                })
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()){
            finished(statuses: list, error: nil)
        }
    }
    
    /**
    *  使用传入的数组，完成网络模型转 Status 数组
    */
    private class func statuses(array:[[String:AnyObject]]) -> [Status]{
        var arrayM = [Status]()
        for dict in array {
            arrayM.append(Status(dict: dict))
        }
        return arrayM
    }
    
}
